<template>
  <v-app>
    <v-main>
      <v-container class="py-6" fluid>
        <!-- Header -->
        <div class="d-flex align-center justify-center mb-6">
          <div class="d-flex align-center ga-3">
            <div class="update-header-icon">
              <v-icon color="primary" :icon="mdiUpdate" size="28"></v-icon>
            </div>
            <div>
              <div class="text-h5 font-weight-bold">{{ appName }}</div>
              <div class="text-subtitle-1 text-medium-emphasis">当前版本 v{{ appVersion }}</div>
            </div>
          </div>
        </div>

        <!-- 统一卡片 -->
        <v-card class="update-card" elevation="2">
          <!-- 状态显示区域 -->
          <v-card-text class="pa-6">
            <!-- 状态图标和标题 -->
            <div class="d-flex align-center justify-center mb-4">
              <div class="status-icon-wrapper">
                <v-icon :color="statusColor" :icon="statusIcon" size="32"></v-icon>
              </div>
            </div>

            <div class="text-center mb-4">
              <div class="text-h6 font-weight-medium mb-1">
                {{ updateStatus.state.status || '未检测' }}
              </div>
              <div class="text-caption text-medium-emphasis">{{ statusDescription }}</div>
            </div>

            <!-- 错误状态 -->
            <div v-if="isError" class="mb-4">
              <v-alert class="rounded-lg" density="comfortable" type="error" variant="tonal">
                <template #prepend>
                  <v-icon :icon="mdiAlertCircle" size="24"></v-icon>
                </template>
                <div class="font-weight-medium">
                  {{ updateStatus.state.msg || '更新检测发生错误' }}
                </div>
                <div class="text-caption text-medium-emphasis mt-2">
                  网络可能不可用或被代理阻断，请检查网络/代理设置后重试。
                  <span v-if="retryCountdown > 0" class="font-weight-medium">
                    将在 {{ retryCountdown }} 秒后自动重试…
                  </span>
                </div>
              </v-alert>
            </div>

            <!-- 状态信息 -->
            <div class="mb-4">
              <div
                v-if="isAvailable"
                class="d-flex align-center ga-2 pa-3 bg-warning-light rounded-lg"
              >
                <v-icon color="warning" :icon="mdiInformation" size="20"></v-icon>
                <span class="text-body-2"
                  >发现新版本：<b>v{{ updateStatus.state.info?.version }}</b
                  >，已开始下载…</span
                >
              </div>
              <div
                v-else-if="noUpdate"
                class="d-flex align-center ga-2 pa-3 bg-success-light rounded-lg"
              >
                <v-icon color="success" :icon="mdiCheckCircle" size="20"></v-icon>
                <span class="text-body-2">当前已是最新版本。</span>
              </div>
              <div v-else-if="notChecked" class="mb-2 text-medium-emphasis text-center">
                点击"检查更新"来检测是否有新版本。
              </div>
              <div v-else-if="isChecking" class="mb-2 text-medium-emphasis text-center">
                正在检查更新…
              </div>
            </div>

            <!-- 下载进度 -->
            <div v-if="isDownloading" class="download-progress mb-4">
              <div class="d-flex align-center justify-space-between mb-2">
                <div class="d-flex align-center ga-2">
                  <v-icon color="primary" :icon="mdiDownload" size="20"></v-icon>
                  <span class="text-body-2 font-weight-medium">正在下载更新包</span>
                </div>
                <div class="text-body-2 font-weight-bold primary-text">
                  {{ updateStatus.state.percent ?? 0 }}%
                </div>
              </div>
              <v-progress-linear
                color="primary"
                height="8"
                :model-value="updateStatus.state.percent ?? 0"
                rounded
                striped
              >
                <template #default="{ value }">
                  <small>{{ Math.ceil(value) }}%</small>
                </template>
              </v-progress-linear>
            </div>

            <!-- 下载完成 -->
            <div v-if="isDownloaded" class="mt-4">
              <v-alert class="rounded-lg" density="comfortable" type="success" variant="tonal">
                <template #prepend>
                  <v-icon :icon="mdiCheckCircle" size="24"></v-icon>
                </template>
                <div class="font-weight-medium">更新包已下载完成，可以立即重启安装。</div>
              </v-alert>
            </div>

            <!-- 版本信息 -->
            <div class="version-info mt-4">
              <div class="d-flex justify-space-between align-center mb-2">
                <div class="d-flex align-center ga-2">
                  <v-icon color="success" :icon="mdiCheckCircle" size="18"></v-icon>
                  <span class="text-body-2 text-medium-emphasis">当前版本</span>
                </div>
                <div class="text-body-2 font-weight-medium success-text">v{{ appVersion }}</div>
              </div>

              <div class="d-flex justify-space-between align-center mb-2">
                <div class="d-flex align-center ga-2">
                  <v-icon color="warning" :icon="mdiCloudDownload" size="18"></v-icon>
                  <span class="text-body-2 text-medium-emphasis">最新版本</span>
                </div>
                <div class="text-body-2 font-weight-medium warning-text">
                  v{{ updateStatus.state.info?.version || '--' }}
                </div>
              </div>

              <div class="d-flex justify-space-between align-center">
                <div class="d-flex align-center ga-2">
                  <v-icon :icon="mdiClockOutline" size="16"></v-icon>
                  <span class="text-body-2 text-medium-emphasis">上次检查</span>
                </div>
                <div class="text-body-2 text-medium-emphasis">
                  {{ lastCheckedText }}
                </div>
              </div>
            </div>
          </v-card-text>

          <v-divider />

          <!-- 操作按钮区域 -->
          <v-card-actions class="pa-4">
            <v-btn
              v-if="canCheck"
              class="text-none flex-grow-1"
              color="primary"
              :loading="isChecking"
              :prepend-icon="mdiRefresh"
              variant="elevated"
              @click="checkUpdate"
            >
              检查更新
            </v-btn>

            <v-btn
              v-if="canInstall"
              class="text-none flex-grow-1"
              color="success"
              :prepend-icon="mdiRestart"
              variant="elevated"
              @click="installAndRestart"
            >
              重启安装
            </v-btn>

            <v-btn
              v-if="isError"
              class="text-none flex-grow-1"
              color="error"
              :prepend-icon="mdiRefresh"
              variant="elevated"
              @click="retryNow"
            >
              重试
            </v-btn>

            <v-btn
              v-if="!isError && !canCheck && !canInstall"
              class="text-none flex-grow-1"
              color="grey"
              :prepend-icon="mdiHistory"
              variant="outlined"
              @click="checkUpdate"
            >
              重新检查
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-container>
    </v-main>
  </v-app>
</template>

<script lang="ts" setup>
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useSystemStateListener } from '@/composables/useSystemStateListener'
import { createRuntimeState } from 'global-state'
import type { updateInfo } from '~types/updater'
import {
  mdiAlertCircle,
  mdiCheckCircle,
  mdiClockOutline,
  mdiCloudDownload,
  mdiDownload,
  mdiHistory,
  mdiInformation,
  mdiInformationOutline,
  mdiLoading,
  mdiRefresh,
  mdiRestart,
  mdiUpdate
} from '@mdi/js'

const appName = process.env.npm_package_name
const appVersion = process.env.npm_package_version

const updateStatus = createRuntimeState<updateInfo>('updateStatus', { status: '未检测' })

// 派生状态
const isChecking = computed(() => updateStatus.state.status === '正在检测')
const isAvailable = computed(() => updateStatus.state.status === '有新版')
const isDownloading = computed(() => updateStatus.state.status === '正在下载')
const isDownloaded = computed(() => updateStatus.state.status === '下载完成')
const isError = computed(() => updateStatus.state.status === '检测出错')
const noUpdate = computed(() => updateStatus.state.status === '无更新')
const notChecked = computed(() => updateStatus.state.status === '未检测')

const canCheck = computed(() => !isDownloading.value && !isDownloaded.value && !isChecking.value)
const canInstall = computed(() => isDownloaded.value)

// 状态描述
const statusDescription = computed(() => {
  switch (updateStatus.state.status) {
    case '有新版': {
      return '发现新版本，正在准备下载'
    }
    case '正在下载': {
      return '正在下载更新包，请稍候'
    }
    case '下载完成': {
      return '更新包已下载完成，可以安装'
    }
    case '检测出错': {
      return '检查更新时发生错误'
    }
    case '无更新': {
      return '当前已是最新版本'
    }
    case '正在检测': {
      return '正在检查是否有新版本'
    }
    default: {
      return '点击检查更新按钮开始'
    }
  }
})

const statusColor = computed(() => {
  switch (updateStatus.state.status) {
    case '有新版': {
      return 'warning'
    }
    case '正在下载': {
      return 'primary'
    }
    case '下载完成': {
      return 'success'
    }
    case '检测出错': {
      return 'error'
    }
    case '无更新': {
      return 'secondary'
    }
    default: {
      return 'default'
    }
  }
})

const statusIcon = computed(() => {
  switch (updateStatus.state.status) {
    case '有新版': {
      return mdiCloudDownload
    }
    case '正在下载': {
      return mdiDownload
    }
    case '下载完成': {
      return mdiCheckCircle
    }
    case '检测出错': {
      return mdiAlertCircle
    }
    case '无更新': {
      return mdiCheckCircle
    }
    case '正在检测': {
      return mdiLoading
    }
    default: {
      return mdiInformationOutline
    }
  }
})

// 上次检查时间 & 自动重试
const lastCheckedAt = ref<number | null>(null)
const retryCountdown = ref(0)
let retryTimer: number | null = null

function setLastChecked() {
  lastCheckedAt.value = Date.now()
}
function formatRelative(ts: number) {
  const diff = Math.floor((Date.now() - ts) / 1000)
  if (diff < 5) return '刚刚'
  if (diff < 60) return `${diff} 秒前`
  const m = Math.floor(diff / 60)
  if (m < 60) return `${m} 分钟前`
  const h = Math.floor(m / 60)
  if (h < 24) return `${h} 小时前`
  const d = new Date(ts)
  try {
    return new Intl.DateTimeFormat('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    }).format(d)
  } catch {
    return d.toLocaleString()
  }
}

const lastCheckedText = computed(() =>
  lastCheckedAt.value ? formatRelative(lastCheckedAt.value) : '—'
)
function clearRetry() {
  if (retryTimer) {
    window.clearInterval(retryTimer)
    retryTimer = null
  }
  retryCountdown.value = 0
}
function startRetry(seconds = 10) {
  clearRetry()
  retryCountdown.value = seconds
  retryTimer = window.setInterval(() => {
    if (retryCountdown.value <= 1) {
      clearRetry()
      checkUpdate()
    } else {
      retryCountdown.value -= 1
    }
  }, 1000)
}
watch(
  () => updateStatus.state.status,
  s => {
    if (s === '无更新' || s === '有新版' || s === '检测出错') setLastChecked()
    if (s === '检测出错') startRetry(10)
    else clearRetry()
  }
)

function checkUpdate() {
  try {
    _pre_.ipcSend('系统检查更新')
  } catch (error) {
    console.error('发送检查更新指令失败', error)
  }
}
function installAndRestart() {
  try {
    _pre_.ipcSend('系统更新并重启')
  } catch (error) {
    console.error('发送安装更新指令失败', error)
  }
}
function retryNow() {
  clearRetry()
  checkUpdate()
}

useSystemStateListener()

onMounted(() => {
  checkUpdate()
})
onUnmounted(() => {
  clearRetry()
})
</script>

<style scoped>
.update-header-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 56px;
  height: 56px;
  border-radius: 16px;
  background: linear-gradient(
    135deg,
    rgba(var(--v-theme-primary), 0.1),
    rgba(var(--v-theme-primary), 0.05)
  );
  backdrop-filter: blur(10px);
}

.status-icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background: rgba(var(--v-theme-surface-variant), 0.5);
}

.update-card {
  border-radius: 16px;
  overflow: hidden;
  max-width: 500px;
  margin: 0 auto;
}

.download-progress {
  animation: fadeIn 0.5s ease;
}

.version-info {
  background-color: rgba(var(--v-theme-surface-variant), 0.3);
  border-radius: 8px;
  padding: 12px;
}

.bg-warning-light {
  background-color: rgba(var(--v-theme-warning), 0.1);
  border-left: 4px solid rgb(var(--v-theme-warning));
}

.bg-success-light {
  background-color: rgba(var(--v-theme-success), 0.1);
  border-left: 4px solid rgb(var(--v-theme-success));
}

.bg-grey-light {
  background-color: rgba(var(--v-theme-surface-variant), 0.3);
  border-left: 4px solid rgba(var(--v-theme-on-surface), 0.3);
}

.bg-primary-light {
  background-color: rgba(var(--v-theme-primary), 0.1);
  border-left: 4px solid rgb(var(--v-theme-primary));
}

.primary-text {
  color: rgb(var(--v-theme-primary));
}

.success-text {
  color: rgb(var(--v-theme-success));
}

.warning-text {
  color: rgb(var(--v-theme-warning));
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 600px) {
  .update-header-icon {
    width: 48px;
    height: 48px;
  }

  .status-icon-wrapper {
    width: 56px;
    height: 56px;
  }

  .update-card {
    margin: 0 12px;
  }
}
</style>
